package org.ljy.forum6.exception;

import lombok.extern.slf4j.Slf4j;
import org.ljy.forum6.common.AppResult;
import org.ljy.forum6.common.ResultCode;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 统一异常处理
 */

@ControllerAdvice
@Slf4j
@ResponseBody
public class GlobalExceptionHandler {
    /**
     * 先捕获自定义的异常信息
     */
    @ExceptionHandler(ApplicationException.class)
    public AppResult applicationException(ApplicationException e) {
        //1.打印异常信息
        e.printStackTrace();
        log.error(e.getMessage());
        //2.返回异常结果
        if(e.getErrorResult()!=null) {
            return e.getErrorResult();
        }
        //2.1.判空
        if(e.getMessage()==null || "".equals(e.getMessage())) {
            return AppResult.failed(ResultCode.ERROR_SERVICES);
        }
        return AppResult.failed(e.getMessage());
    }

    /**
     * 再进行兜底异常信息捕获
     */
    @ExceptionHandler(Exception.class)
    public AppResult exceptionHandler(Exception e) {
        //1.打印异常信息
        e.printStackTrace();
        log.error(e.getMessage());
        //2.返回异常结果
        if(e.getMessage()==null || "".equals(e.getMessage())) {
            return AppResult.failed(ResultCode.ERROR_SERVICES);
        }
        return AppResult.failed(e.getMessage());
    }

}
